package com.heima.controller;

import com.heima.component.RedisComponent;
import com.heima.entity.config.AppConfig;
import com.heima.entity.constants.Constants;
import com.heima.entity.dto.DownloadFileDto;
import com.heima.entity.enums.FileFolderTypeEnums;
import com.heima.entity.enums.FileTypeEnums;
import com.heima.entity.enums.ResponseCodeEnum;
import com.heima.entity.po.FileInfo;
import com.heima.entity.query.FileInfoQuery;
import com.heima.entity.vo.ResponseVO;
import com.heima.exception.BusinessException;
import com.heima.service.FileInfoService;
import com.heima.utils.StringTools;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class CommonFileController extends ABaseController{
    @Resource
    private AppConfig appConfig;

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private RedisComponent redisComponent;
    public void getImage(HttpServletResponse response,String imageFolder,String imageName){
        if(StringTools.isEmpty(imageFolder) || StringTools.isEmpty(imageName) || !StringTools.pathIsOk(imageFolder) || !StringTools.pathIsOk(imageName)){
            return;
        }
        String imageSuffix = StringTools.getFileSuffix(imageName);
        String filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + imageFolder + "/" + imageName;
        imageSuffix = imageSuffix.replace(".","");
        String contenType = "image/" + imageSuffix;
        response.setContentType(contenType);
        response.setHeader("Cache-Control","max-age=2592000");
        readFile(response,filePath);

    }
    public void getFile(HttpServletResponse response,String fileId,String userId) {
        String filePath = null;
        if (fileId.endsWith(".ts")){
            String[] ts = fileId.split("_");
            String realFileId = ts[0];
            FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(realFileId, userId);
            filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + StringTools.getFileNameNoSuffix(fileInfo.getFilePath()) + "/" + fileId;
        }
        else {
            FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(fileId, userId);
        if (fileInfo == null) {
            throw new BusinessException("文件不存在");

        }

        if (fileInfo.getFileCategory() == FileTypeEnums.VIDEO.getType()) {
            filePath = fileInfo.getFilePath();
            String fileNameNoSuffix = StringTools.getFileNameNoSuffix(filePath);
            filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileNameNoSuffix + "/" + Constants.M3U8_NAME;
        }
        else {
            filePath = fileInfo.getFilePath();
            filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + filePath;
        }
        File file = new File(filePath);
        if (!file.exists()){
            throw new BusinessException("m3u8文件不存在");
        }

    }
        readFile(response,filePath);
    }

    public ResponseVO getFolderInfo(String path,String userId){
        String[] pathArray = path.split("/");
        FileInfoQuery infoQuery = new FileInfoQuery();
        infoQuery.setUserId(userId);
        infoQuery.setFileIdArray(pathArray);
        infoQuery.setFolderType(FileFolderTypeEnums.FOLDER.getType());
        String orderBy = "field(file_id,\"" + StringUtils.join(pathArray, "\",\"") + "\")";
        infoQuery.setOrderBy(orderBy);
        List<FileInfo> fileInfoList = fileInfoService.findListByParam(infoQuery);
        return getSuccessResponseVO(fileInfoList);
    }

    protected ResponseVO createDownloadUrl(String fileId,String userId){
        FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(fileId, userId);
        if (fileInfo == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        if (FileFolderTypeEnums.FOLDER.getType().equals(fileInfo.getFolderType())){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        String code = StringTools.getRandomString(Constants.LENGTH_50);

        DownloadFileDto dto = new DownloadFileDto();
        dto.setDownloadCode(code);
        dto.setFileId(fileId);
        dto.setFileName(fileInfo.getFileName());
        dto.setFilePath(fileInfo.getFilePath());

        redisComponent.saveDownloadCode(code,dto);


        return getSuccessResponseVO(code);
    }
    protected void download(HttpServletRequest request, HttpServletResponse response, String code) throws Exception {
        DownloadFileDto downloadFileDto = redisComponent.getDownloadCode(code);
        if (null == downloadFileDto) {
            return;
        }
        String filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + downloadFileDto.getFilePath();
        String fileName = downloadFileDto.getFileName();
        response.setContentType("application/x-msdownload; charset=UTF-8");
        if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {//IE浏览器
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        readFile(response, filePath);
    }
}
